<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户id" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入用户id" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证" prop="idCard">
        <el-input v-model="queryParams.idCard" placeholder="请输入身份证" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所在地址" prop="address">
        <el-input v-model="queryParams.address" placeholder="请输入所在地址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:user:add']"
        >新增
        </el-button>
      </el-col>
      &lt;!&ndash;      <el-col :span="1.5">&ndash;&gt;
      &lt;!&ndash;        <el-button&ndash;&gt;
      &lt;!&ndash;          type="success"&ndash;&gt;
      &lt;!&ndash;          plain&ndash;&gt;
      &lt;!&ndash;          icon="el-icon-edit"&ndash;&gt;
      &lt;!&ndash;          size="mini"&ndash;&gt;
      &lt;!&ndash;          :disabled="single"&ndash;&gt;
      &lt;!&ndash;          @click="handleUpdate"&ndash;&gt;
      &lt;!&ndash;          v-hasPermi="['system:user:edit']"&ndash;&gt;
      &lt;!&ndash;        >修改</el-button>&ndash;&gt;
      &lt;!&ndash;      </el-col>&ndash;&gt;
&lt;!&ndash;      <el-col :span="1.5">&ndash;&gt;
&lt;!&ndash;        <el-button&ndash;&gt;
&lt;!&ndash;          type="danger"&ndash;&gt;
&lt;!&ndash;          plain&ndash;&gt;
&lt;!&ndash;          icon="el-icon-delete"&ndash;&gt;
&lt;!&ndash;          size="mini"&ndash;&gt;
&lt;!&ndash;          :disabled="multiple"&ndash;&gt;
&lt;!&ndash;          @click="handleDelete"&ndash;&gt;
&lt;!&ndash;          v-hasPermi="['system:user:remove']"&ndash;&gt;
&lt;!&ndash;        >删除&ndash;&gt;
&lt;!&ndash;        </el-button>&ndash;&gt;
&lt;!&ndash;      </el-col>&ndash;&gt;
      &lt;!&ndash;      <el-col :span="1.5">&ndash;&gt;
      &lt;!&ndash;        <el-button&ndash;&gt;
      &lt;!&ndash;          type="warning"&ndash;&gt;
      &lt;!&ndash;          plain&ndash;&gt;
      &lt;!&ndash;          icon="el-icon-download"&ndash;&gt;
      &lt;!&ndash;          size="mini"&ndash;&gt;
      &lt;!&ndash;          @click="handleExport"&ndash;&gt;
      &lt;!&ndash;          v-hasPermi="['system:user:export']"&ndash;&gt;
      &lt;!&ndash;        >导出</el-button>&ndash;&gt;
      &lt;!&ndash;      </el-col>&ndash;&gt;
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" type="index" width="50" align="center" prop="id" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="身份证" align="center" prop="idCard" />
      <el-table-column label="所在地址" align="center" prop="address" />
      <el-table-column label="工作经历" align="center" prop="workExperience" width="400">
        <template slot-scope="scope">
          <div
            v-if="scope.row.workExperience"
            style="display: flex; flex-wrap: wrap; align-items: center; justify-content: center;"
          >
            <template v-for="(item, index) in parseFiles(scope.row.workExperience)">
              <template v-if="isImage(item)">
                <!-- 是图片就预览 -->
                <image-preview
                  :src="scope.row.workExperience"
                  :width="50"
                  :height="50"
                  :key="`img-${index}`"
                />
              </template>
              <template v-else>
                <!-- 非图片，显示链接 -->
                <a
                  :href="getFileName(item)"
                  target="_blank"
                  style="margin: 0 5px;"
                  :key="`link-${index}`"
                >
                  文件{{ index + 1 }}
                </a>
              </template>

              <!-- 添加分隔符 -->
              <span v-if="index !== parseFiles(scope.row.workExperience).length - 1" style="margin: 0 5px;">|</span>
            </template>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="是否通过" align="center" prop="processStatus" :formatter="formatProcessStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleAll(scope.row)">查看
          </el-button>
          <el-button v-if="scope.row.processStatus != '0'" size="mini" type="text" icon="el-icon-edit"
            @click="handleCross(scope.row)">通过
          </el-button>
          <el-button v-if="scope.row.processStatus != '0'" size="mini" type="text" icon="el-icon-delete"
            @click="handleReject(scope.row)">驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open2" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <!-- 左边列 -->
          <el-col :span="12">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="form.userId" disabled />
            </el-form-item>
            <el-form-item label="手机号" prop="username">
              <el-input v-model="form.username" disabled />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" disabled />
            </el-form-item>
            <el-form-item label="年龄" prop="age">
              <el-input v-model="form.age" disabled />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-input v-model="form.gender" disabled />
            </el-form-item>
            <el-form-item label="身份证" prop="idCard">
              <el-input v-model="form.idCard" disabled />
            </el-form-item>
            <el-form-item label="邀请码" prop="invitationCode">
              <el-input v-model="form.invitationCode" disabled />
            </el-form-item>
          </el-col>

          <!-- 右边列 -->
          <el-col :span="12">
            <el-form-item label="头像" prop="imageAddress">
              <image-preview :src="form.imageAddress" :width="50" :height="50" disabled/>
            </el-form-item>
            <el-form-item label="所在地址" prop="address">
              <el-input v-model="form.address" disabled />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="form.nickname" disabled />
            </el-form-item>
            <el-form-item label="邀请人id" prop="inviterId">
              <el-input v-model="form.inviterId" disabled />
            </el-form-item>
            <el-form-item label="简历" prop="workExperience">
              <div v-for="(item, index) in splitWorkExperience" :key="index" style="margin-bottom: 8px;" disabled>
                <template v-if="isImage(item)">
                  <!-- 是图片就预览 -->
                  <image-preview :src="item" :width="60" :height="60" />
                </template>
                <template v-else>
                  <!-- 是文件就提供下载链接 -->
                  <el-link :href="getFileName(item)" target="_blank">文件{{ index + 1 }}</el-link>
                </template>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider></el-divider>

        <div class="form-section-title">工作经历</div>
        <el-table
          height="200px"
          :data="form.workExperiences"
          border
          style="width: auto;"
          v-if="form.workExperiences && form.workExperiences.length"
        >
          <el-table-column prop="startTime" label="开始日期" align="center" />
          <el-table-column prop="endTime" label="结束日期" align="center" />
          <el-table-column prop="companyName" label="公司名称" align="center" />
          <el-table-column prop="product" label="负责产品" align="center" />
          <el-table-column prop="hospitalName" label="医院名称" align="center" />
          <el-table-column prop="department" label="科室" align="center" />
        </el-table>
        <div v-else>暂无数据</div>

        <el-divider></el-divider>

        <div class="form-section-title">病种</div>
        <el-table
          height="200px"
          :data="form.diseaseList"
          border
          style="width: auto;"
          v-if="form.diseaseList && form.diseaseList.length"
        >
          <el-table-column prop="illnessName" label="病种" align="center" />
          <el-table-column prop="synopsis" label="简介" align="center" />
          <el-table-column prop="price" label="价格" align="center" />
        </el-table>
        <div v-else>暂无数据</div>

        <el-divider></el-divider>

        <div class="form-section-title">病种</div>
        <el-table height="200px" :data="form.diseaseList" border style="width: auto;" v-if="form.diseaseList && form.diseaseList.length">
          <el-table-column prop="illnessName" label="病种" align="center" />
          <el-table-column prop="synopsis" label="简介" align="center" />
          <el-table-column prop="price" label="价格" align="center" />
        </el-table>
        <div v-else>暂无数据</div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, updatePassword, updateProcessStatus } from "@/api/expert/expert"
import { listDisease } from "@/api/disease/disease"
import {isExternal} from "@/utils/validate";
export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      open1: false,
      open2: false,
      // 【请填写功能名称】表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        username: null,
        name: null,
        age: null,
        gender: null,
        idCard: null,
        invitationCode: null,
        password: null,
        imageAddress: null,
        isExpert: null,
        address: null,
        isPublic: null,
        nickname: null,
        inviterId: null,
        workExperience: null,
        userStatus: null,
        processStatus: null,
        ddTotalNumber: null,
        totalAmount: null,
        diseaseIds: []
      },
      // 表单参数
      form: {
        incomeList: [],
        ddDetailsList: [],
        iuserList: [],
        expertList: [],
        diseaseList: [],
        diseaseIds: []
      },
      diseases: [],
      password: null,
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.getList()
  },
  computed: {
    splitWorkExperience() {
      if (!this.form.workExperience) return [];
      return this.form.workExperience.split(',').map(s => s.trim()).filter(Boolean);
    }
  },
  methods: {
    parseFiles(value) {
      if (!value) return [];
      return value.split(',').map(item => item.trim());
    },
    isImage(url) {
      return /\.(png|jpe?g|gif|bmp|webp)$/i.test(url);
    },
    getFileName(url) {
      console.log(url)
      return process.env.VUE_APP_BASE_API + url
    },
    handleCross(row) {
      row.processStatus = '0'
      console.log(row)
      updateProcessStatus(row).then(response => {
        this.getList()
        this.$modal.msgSuccess("审核通过")
      })
    },
    handleReject(row) {
      row.processStatus = '1'
      console.log(row)
      updateProcessStatus(row).then(response => {
        this.getList()
        this.$modal.msgSuccess("审核驳回")
      })
    },
    formatProcessStatus(row, column, cellValue) {
      switch (cellValue) {
        case '0':
          return '通过';
        case '1':
          return '驳回';
        case '2':
          return '待审核';
      }
    },
    handleToggleStatus(row) {
      console.log(row);
      // 根据当前状态切换
      if (row.userStatus === '0') {
        // 执行禁用操作
        row.userStatus = '1';  // 更新为禁用状态
        updateUser(row).then(response => {
          this.getList()
        })
        this.$message.success('已禁用');
      } else {
        // 执行启用操作
        row.userStatus = '0';  // 更新为启用状态
        updateUser(row).then(response => {
          this.getList()
        })
        this.$message.success('已启用');
      }
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      this.queryParams.isExpert = 0
      this.queryParams.processStatus = '2'
      listUser(this.queryParams).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    }
    ,
    // 取消按钮
    cancel() {
      this.open = false
      this.open1 = false
      this.open2 = false
      this.reset()
    }
    ,
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        username: null,
        name: null,
        age: null,
        gender: null,
        idCard: null,
        invitationCode: null,
        password: null,
        imageAddress: null,
        isExpert: null,
        address: null,
        isPublic: null,
        nickname: null,
        inviterId: null,
        workExperience: null,
        createTime: null,
        userStatus: null,
        processStatus: null,
        ddTotalNumber: null,
        totalAmount: null
      }
      this.resetForm("form")
    }
    ,
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    }
    ,
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    }
    ,
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
    ,
    /** 新增按钮操作 */
    handleAdd() {
      this.diseases = []
      listDisease().then(response => {
        console.log(1111, response.rows)
        this.diseases = response.rows
      })
      this.reset()
      this.open = true
      this.title = "添加【专家信息】"
    }
    ,
    handleAll(row) {
      this.reset()
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data
        this.open2 = true
        this.title = "【详情】"
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data
        this.open1 = true
        this.title = "修改密码"
      })
    }
    ,
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            const isPublic = this.form.isPublic;
            if (isPublic === '是') {
              this.form.isPublic = 0;
            } else if (isPublic === '否') {
              this.form.isPublic = 1;
            } else if (isPublic === '不限') {
              this.form.isPublic = 2;
              // 可选：这里可以加一个 else 处理其他情况
            }

            const isExpert = this.form.isExpert;
            if (isExpert === '是') {
              this.form.isExpert = 0;
            } else if (isExpert === '否') {
              this.form.isExpert = 1;
              // 可选：这里可以加一个 else 处理其他情况
            }
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })

          }
        }
      })
    }
    ,
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除【专家】编号为"' + ids + '"的数据项？').then(function () {
        return delUser(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    }
    ,
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
